package jmine.tec.web.wicket.security;

import jmine.tec.security.permission.PermissionCheckerFactory;

import org.apache.wicket.Component;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;

/**
 * {@link IAuthorizationStrategy} que verifica as classes pela anotacao Secure
 * 
 * @author takeshi
 */
public class SecurityServiceAuthorizationStrategy implements IAuthorizationStrategy {

    private PermissionCheckerFactory permissionCheckerFactory;

    /**
     * {@inheritDoc}
     */
    public boolean isActionAuthorized(Component component, Action action) {
        if (component instanceof BookmarkablePageLink<?>) {
            BookmarkablePageLink<?> link = (BookmarkablePageLink<?>) component;
            if (link.getPageClass() != null) {
                boolean hasPermission = this.permissionCheckerFactory.currentUserHasPermission(link.getPageClass());
                link.setVisibilityAllowed(hasPermission);
                return hasPermission;
            }
        }

        return this.permissionCheckerFactory.currentUserHasPermission(component.getClass());
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.apache.wicket.authorization.IAuthorizationStrategy#isInstantiationAuthorized(java.lang.Class)
     */
    public <T extends Component> boolean isInstantiationAuthorized(Class<T> componentClass) {
        return this.permissionCheckerFactory.currentUserHasPermission(componentClass);
    }

    /**
     * @param permissionCheckerFactory the permissionCheckerFactory to set
     */
    public void setPermissionCheckerFactory(PermissionCheckerFactory permissionCheckerFactory) {
        this.permissionCheckerFactory = permissionCheckerFactory;
    }
}
